var express = require('express');
const multer = require('multer') // v1.0.5
const upload = multer() // for parsing multipart/form-data

var router = express.Router();
const OpenAI = require('openai')

let apiKey = 'a569f564-7dad-4811-88c5-f9623e5ac2a3';
let model ='doubao-seed-1-6-thinking-250615'
const openai = new OpenAI({
    apiKey: apiKey,
    baseURL: 'https://ark.cn-beijing.volces.com/api/v3',
});


/**
 * @swagger
 * components:
 *   schemas:
 *     ImageContent:
 *       type: object
 *       properties:
 *         type:
 *           type: string
 *           enum: [image_url]
 *         image_url:
 *           type: object
 *           properties:
 *             url:
 *               type: string
 *               format: uri
 *               description: 图像URL
 *           required:
 *             - url
 *       required:
 *         - type
 *         - image_url
 *     
 *     TextContent:
 *       type: object
 *       properties:
 *         type:
 *           type: string
 *           enum: [text]
 *         text:
 *           type: string
 *           description: 文本内容
 *       required:
 *         - type
 *         - text
 *     
 *     MessageContent:
 *       type: array
 *       items:
 *         oneOf:
 *           - $ref: '#/components/schemas/ImageContent'
 *           - $ref: '#/components/schemas/TextContent'
 *     
 *     Message:
 *       type: object
 *       properties:
 *         role:
 *           type: string
 *           enum: [user, assistant]
 *         content:
 *           $ref: '#/components/schemas/MessageContent'
 *       required:
 *         - role
 *         - content
 *     
 *     MessagesRequest:
 *       type: object
 *       properties:
 *         messages:
 *           type: array
 *           items:
 *             $ref: '#/components/schemas/Message'
 *       required:
 *         - messages
 *     
 *     Response:
 *       type: object
 *       properties:
 *         message:
 *           type: string
 *           description: 响应消息
 *       required:
 *         - message
 */



/**
 * @swagger
 * /search/doubao:
 *   post :
 *     summary: Create a new user
 *     tags: [doubao]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *          schema:
 *           $ref: '#/components/schemas/MessagesRequest'
 *          example:
 *             messages:
 *               - role: 'user'
 *                 content:
 *                   - type: 'image_url'
 *                     image_url:
 *                       url: 'https://ark-project.tos-cn-beijing.ivolces.com/images/view.jpeg'
 *                   - type: 'text'
 *                     text: '这是哪里？'
 *     responses:
 *       201:
 *         description: The user was successfully created
 *         content:
 *           application/json:

 *       500:
 *         description: Some server error
 */
router.post('/doubao', async function (req, res, next) {
  try {
    // 输入验证
    if (!req.body || !req.body.messages || !Array.isArray(req.body.messages)) {
      return res.status(400).json({
        status: 400,
        error: 'Invalid request format. messages must be an array.'
      });
    }
    
    console.log('Received chat request with', req.body.messages.length, 'messages');
    
    // 设置响应头
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');
    
    // 调用OpenAI API
    const response = await openai.chat.completions.create({
      apiKey: apiKey,
      messages: req.body.messages,
      model: model,
      stream: true
    });
    
    // 使用 for-await-of 处理流式响应
    for await (const chunk of response) {
      const content = chunk.choices[0]?.delta?.content;
      if (content) {
        res.write(`data: ${JSON.stringify({ content })}\n\n`);
      }
    }
    
    res.end();
    
  } catch (error) {
    console.error('Server error:', error);
    res.status(500).json({
      status: 500,
      error: 'Internal Server Error'
    });
  }
});



module.exports = router;
